package com.heatup.apt.api.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.heatup.apt.api.service.*;
import com.heatup.apt.common.constants.*;
import com.heatup.apt.common.constants.ServiceConstans.ServiceType;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.coach.CoachInfoMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.dao.user.UserDiscountMapper;
import com.heatup.apt.common.dao.user.UserInfoMapper;
import com.heatup.apt.common.dao.user.UserProductServiceMapper;
import com.heatup.apt.common.util.DateUtil;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.model.CityDiscount;
import com.heatup.apt.model.DataDict;
import com.heatup.apt.model.api.ServicePriceResultModel;
import com.heatup.apt.model.api.product.VipProductModel;
import com.heatup.apt.model.api.store.StoreResultModel;
import com.heatup.apt.model.coach.CoachInfo;
import com.heatup.apt.model.company.CompanyStaff;
import com.heatup.apt.model.course.CourseInfo;
import com.heatup.apt.model.course.CourseInfoModel;
import com.heatup.apt.model.course.CourseSchedule;
import com.heatup.apt.model.course.CourseStore;
import com.heatup.apt.model.product.ProductService;
import com.heatup.apt.model.product.ProductServiceDetail;
import com.heatup.apt.model.product.ServicePrice;
import com.heatup.apt.model.product.ServicePriceExample;
import com.heatup.apt.model.store.StoreInfo;
import com.heatup.apt.model.user.UserDiscount;
import com.heatup.apt.model.user.UserInfo;
import com.heatup.apt.model.user.UserProductService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 产品价格服务
 *
 * @author Jindaodaxia
 */
@Service
public class ProductServiceImpl implements ProductServiceInterface {


    private static final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private ServicePriceMapper servicePriceMapper;
    @Autowired
    private StoreInfoMapper storeInfoMapper;
    @Autowired
    private CourseInfoMapper courseInfoMapper;
    @Autowired
    private CourseScheduleMapper courseScheduleMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private CourseStoreMapper courseStoreMapper;
    @Autowired
    private UserDiscountMapper userDiscountMapper;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private CityDiscountMapper cityDiscountMapper;
    @Autowired
    private CompanyStaffMapper companyStaffMapper;
    
    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductServiceDetailMapper productServiceDetailMapper;
    @Autowired
    private ProductServiceMapper productServiceMapper;
    @Autowired
    private UserProductServiceMapper userProductServiceMapper;
    @Autowired
    private CoachInfoMapper coachInfoMapper;
    
    @Autowired
    private UserProductServiceService userProductServiceService;

    @Autowired
    private UserCourseVipServiceService userCourseVipServiceService;


    @Override
    public List<ServicePrice> queryPriceByTypeAndLevel(int serviceType, int level) {
        ServicePriceExample servicePriceExample = new ServicePriceExample();
        servicePriceExample.or().andServiceTypeEqualTo(serviceType).andLevelEqualTo(level);
        List<ServicePrice> list = servicePriceMapper.selectByExample(servicePriceExample);
        return list;
    }

    /**
     * 查询产品详情(提交订单前)
     *
     * @param userLevel   用户会员等级
     * @param serviceType 课程类型
     * @param storeId     门店Id
     * @param courseId    订单ID
     * @param userInfo    用户信息
     * @param longitudeLatitude 用户经纬度
     * @return 产品详情
     */
    @Override
    public Map<String, Object> getProductList(int userLevel, int serviceType, int storeId, int courseId, UserInfo userInfo, String longitudeLatitude) {
        Map<String, Object> map = new HashMap<>();
        //UserProductService userProductService = userProductServiceService.queryUserProductServiceByUserIdAndType(userInfo.getId(), UserProductServiceConstants.SELFTYPESERVICE);
        Integer hasYearCardService = userProductServiceService.checkUserHasYearCardService(userInfo.getId());
        logger.info("getProductList userLevel:" + userLevel);
        
        if (serviceType == ServiceType.selfFitness.getIndex()) {
        	// 自助
            map = getSelfFitnessList(userInfo.getId(), userLevel, serviceType, storeId, courseId, longitudeLatitude);
        }
        if (serviceType == ServiceType.teamCourse.getIndex()) {
        	// 团课
            map = getTeamCoureseList(userLevel, serviceType, storeId, courseId, userInfo, hasYearCardService);
        }
        if (serviceType == ServiceType.privateCourse.getIndex()) {
        	// 私教
            map = getPrivateCourseList(userLevel, serviceType, storeId, courseId , userInfo, hasYearCardService);
        }
        if (serviceType == ServiceType.campCourse.getIndex()) {
            //檬营
            map = getCampCoureseList(userLevel, serviceType, storeId, courseId, userInfo, hasYearCardService);
        }
        if(serviceType == ServiceType.physicalCoupon.getIndex() 
        		|| serviceType == ServiceType.privatePhysical.getIndex()){
        	map = getPhysicalCouponList(userLevel, serviceType, storeId, courseId ,userInfo, hasYearCardService);
        }

        if (serviceType == ServiceType.physicalCoupon.getIndex()) {
            //私教体测
            map.put("isCanOrderLimit", orderInfoMapper.queryPrivateBodyExaminationOrderMaxLimitByToDay());
        }
        if (serviceType == ServiceType.privatePhysical.getIndex()) {
            //私教体验
            map.put("isCanOrderLimit", orderInfoMapper.queryPrivateExperienceOrderMaxLimitByToDay());
        }

        
        //查询该用户是否有企业储值卡 及所属企业是否有效 有效就加入返回 2017-01-16 blank
        CompanyStaff companyStaff = companyStaffMapper.selectCompanyPaymentDetailByUserId(userInfo.getId());
        if (companyStaff != null && companyStaff.getStatus() != null && companyStaff.getStatus() == 0) {
            if (companyStaff.getIsBuyTypeLimit() != null) {
                if (companyStaff.getIsBuyTypeLimit() == 0) {
                    //限制购买课程
                    //团课
                    if (companyStaff.getLimitTeamCourse() != null
                            && companyStaff.getLimitTeamCourse() != null && companyStaff.getLimitTeamCourse() == 1
                            && serviceType == ServiceType.teamCourse.getIndex()) {
                        map.put("companyAccountAmount", companyStaff);
                    }
                    //私教
                    if (companyStaff.getLimitSecretCourse() != null
                            && companyStaff.getLimitSecretCourse() != null && companyStaff.getLimitSecretCourse() == 1
                            && serviceType == ServiceType.privateCourse.getIndex()) {
                        map.put("companyAccountAmount", companyStaff);
                    }
                    //檬营
                    if (companyStaff.getLimitCampCourse() != null
                            && companyStaff.getLimitCampCourse() != null && companyStaff.getLimitCampCourse() == 1
                            && serviceType == ServiceType.campCourse.getIndex()) {
                        map.put("companyAccountAmount", companyStaff);
                    }
                    //自助
                    if (companyStaff.getLimitSelfCourse() != null
                            && companyStaff.getLimitSelfCourse() != null && companyStaff.getLimitSelfCourse() == 1
                            && serviceType == ServiceType.selfFitness.getIndex()) {
                        map.put("companyAccountAmount", companyStaff);
                    }
                } else if (companyStaff.getIsBuyTypeLimit() == 1) {
                    //不限制购买课程
                    map.put("companyAccountAmount", companyStaff);
                }
            }
        }
        
        // 计算99元包月卡剩余天数 5 天倒计时
        try {
        	if(userInfo.getLevel() == UserConstants.UserLevel.vip.getIndex()){
        		int day_num = DateUtils.daysBetween(new Date(),userInfo.getVipEndTime() == null ? new Date():userInfo.getVipEndTime());
            	if(day_num > 0  && day_num <= 5){
            		map.put("surplusDay", day_num);
                }
        	}
		} catch (Exception e) {
			logger.error("================getTeamCoureseList  日期转化失败 ==========================");
		}
        //查询用户距离
        if (StringUtils.isNotBlank(longitudeLatitude)) {
            Map<String, Object> params = new HashMap<>();
            if(StringUtils.isNotBlank(longitudeLatitude) && longitudeLatitude.split(",").length == 2){
                params.put("latitude", longitudeLatitude.split(",")[0]);
                params.put("longitude", longitudeLatitude.split(",")[1]);
                params.put("storeId", storeId);
            }
            map.put("distance",storeInfoMapper.queryStoreDistance(params));
        }
        map.put("level", userLevel);
        map.put("userAccount", userInfo.getAccountAmt());
        return map;
    }

    /**
     * 自助健身产品表
     *
     * @param userId 用户信息
     * @param serviceType 服务类型
     * @param storeId 门店 ID
     * @param courseId 课程 ID
     * @param longitudeLatitude 当前经纬度
     * @return
     */
    private Map<String, Object> getSelfFitnessList(Integer userId, int userLevel , int serviceType, int storeId, int courseId, String longitudeLatitude) {


        logger.info("====Method getSelfFitnessList() start==== ");
        logger.info("The parameters :" + "userLevel:" + userLevel + " serviceType : " + serviceType + " storeId : " + storeId + " courseId : " + courseId + " longitudeLatitude : " + longitudeLatitude);

        Map<String, Object> map = new HashMap<>();

        // and jxy  获取门店自助健身的价钱
        ServicePrice servicePrice = this.queryServicePrice(UserConstants.UserLevel.user.getIndex(), serviceType, storeId, courseId);
        List<DataDict> dataDicts = dataDictService.queryDataDicts(DataDictConstants.DICT_TYPE_SELF_FITNESS_TIME);
        // 查询折扣
        CityDiscount cityDiscount = cityDiscountMapper.queryCityDiscountByStoreId(servicePrice.getStoreId());
        if (servicePrice != null) {
            BigDecimal primePrice = servicePrice.getPrimePrice();
            BigDecimal price = (BigDecimal) (servicePrice.getPrice() == null ? primePrice : servicePrice.getPrice());
            //服务信息
            map.put("serviceName", servicePrice.getServiceName());
            map.put("systemTime", DateUtils.format(new Date(), DateUtils.datePatternAllHH));
            //根据数据字典中配置的自主健身时长来计算价格
            List<Map<String, Object>> resultList = new ArrayList<>();
            if (dataDicts != null && dataDicts.size() > 0) {
                for (DataDict dataDict : dataDicts) {
                    Map<String, Object> mapItem = new HashMap<>();
                    mapItem.put("id", servicePrice.getId());
                    mapItem.put("duration", dataDict.getDictName());
                    if (userLevel == 2) {
                        if (servicePrice.getPrice() != null) {
                            price = servicePrice.getPrice().multiply(BigDecimal.valueOf(Double.valueOf(dataDict.getDictCode())));
                        } else {
                            price = servicePrice.getPrimePrice().multiply(BigDecimal.valueOf(Double.valueOf(dataDict.getDictCode()))).multiply(cityDiscount.getVipDiscount());
                        }
                        primePrice = servicePrice.getPrimePrice().multiply(BigDecimal.valueOf(Double.valueOf(dataDict.getDictCode())));
                        mapItem.put("price", price.setScale(2, BigDecimal.ROUND_HALF_UP));
                        mapItem.put("primePrice", primePrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                        mapItem.put("unitPrice", primePrice.setScale(2, BigDecimal.ROUND_HALF_UP));
                        map.put("discount", cityDiscount.getVipDiscount());
                    } else {
                        mapItem.put("price", price);
                        mapItem.put("primePrice", primePrice.multiply(BigDecimal.valueOf(Double.valueOf(dataDict.getDictCode()))).setScale(2, BigDecimal.ROUND_HALF_UP));
                        mapItem.put("unitPrice", primePrice.multiply(BigDecimal.valueOf(Double.valueOf(dataDict.getDictCode()))).setScale(2, BigDecimal.ROUND_HALF_UP));
                        map.put("discount", cityDiscount.getDiscount());// 1 表示原价
                    }
                    resultList.add(mapItem);
                }
            }
            map.put("list", resultList);

            //门店列表
            Map<String, Object> paramMap = new HashMap<>();
            if(StringUtils.isNotBlank(longitudeLatitude) && longitudeLatitude.split(",").length == 2){
                paramMap.put("latitude", longitudeLatitude.split(",")[0]);
                paramMap.put("longitude", longitudeLatitude.split(",")[1]);
            }
            List isSelfFintnessList = new ArrayList<String>();
            //仅查询支持自助的门店
            isSelfFintnessList.add("1");
            isSelfFintnessList.add("2");
            paramMap.put("status", 2);
            paramMap.put("userId", userId);
            paramMap.put("isSelfFintnessList",isSelfFintnessList);
            List<StoreResultModel> storeList = storeInfoMapper.queryAllStore(paramMap);
            for (StoreResultModel storeInfo : storeList) {
                if (storeInfo.getIs24Hours() == null || (storeInfo.getIs24Hours() != null && storeInfo.getIs24Hours() == 2) ) {
                    //非24小时营业门店才有开始结束时间
                    storeInfo.setOpenTime(DateUtil.formatDate(storeInfo.getOpenTimeD(), DateUtil.FMT_DATE_HHMM) + "~" + DateUtil.formatDate(storeInfo.getCloseTimeD(), DateUtil.FMT_DATE_HHMM));
                }
            }
            map.put("storeList", storeList);
                //查询2天内的自助健身订单量
                /**
                OrderSelfCountInfo self = orderDetailMapper.querySelfOrderCountFor2days(storeId);
                if (self != null) {
                    Integer maxCount = self.getMaxCount();
                    if (maxCount != null && maxCount !=0) {
                        self.setA1100s(self.getA1100() / (double)maxCount >= 0.8 ? self.getA1100() / maxCount == 1 ? 3 : 2 : 1);// 1正常 2 紧张 3满额
                        self.setA1120s(self.getA1120() / (double)maxCount >= 0.8 ? self.getA1120() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1140s(self.getA1140() / (double)maxCount >= 0.8 ? self.getA1140() / maxCount == 1 ? 3 : 2 : 1);

                        self.setA1200s(self.getA1200() / (double)maxCount >= 0.8 ? self.getA1200() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1220s(self.getA1220() / (double)maxCount >= 0.8 ? self.getA1220() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1240s(self.getA1240() / (double)maxCount >= 0.8 ? self.getA1240() / maxCount == 1 ? 3 : 2 : 1);

                        self.setA1300s(self.getA1300() / (double)maxCount >= 0.8 ? self.getA1300() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1320s(self.getA1320() / (double)maxCount >= 0.8 ? self.getA1320() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1340s(self.getA1340() / (double)maxCount >= 0.8 ? self.getA1340() / maxCount == 1 ? 3 : 2 : 1);

                        self.setA1700s(self.getA1700() / (double)maxCount >= 0.8 ? self.getA1700() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1720s(self.getA1720() / (double)maxCount >= 0.8 ? self.getA1720() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1740s(self.getA1740() / (double)maxCount >= 0.8 ? self.getA1740() / maxCount == 1 ? 3 : 2 : 1);

                        self.setA1800s(self.getA1800() / (double)maxCount >= 0.8 ? self.getA1800() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1820s(self.getA1820() / (double)maxCount >= 0.8 ? self.getA1820() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1840s(self.getA1840() / (double)maxCount >= 0.8d ? self.getA1840() / maxCount == 1 ? 3 : 2 : 1);

                        self.setA1900s(self.getA1900() / (double)maxCount >= 0.8 ? self.getA1900() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1920s(self.getA1920() / (double)maxCount >= 0.8 ? self.getA1920() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA1940s(self.getA1940() / (double)maxCount >= 0.8 ? self.getA1940() / maxCount == 1 ? 3 : 2 : 1);

                        self.setA2000s(self.getA2000() / (double)maxCount >= 0.8 ? self.getA2000() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA2020s(self.getA2020() / (double)maxCount >= 0.8 ? self.getA2020() / maxCount == 1 ? 3 : 2 : 1);
                        self.setA2040s(self.getA2040() / (double)maxCount >= 0.8 ? self.getA2040() / maxCount == 1 ? 3 : 2 : 1);


                        self.setB1100s(self.getB1100() / (double)maxCount >= 0.8 ? self.getB1100() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1120s(self.getB1120() / (double)maxCount >= 0.8 ? self.getB1120() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1140s(self.getB1140() / (double)maxCount >= 0.8 ? self.getB1140() / maxCount == 1 ? 3 : 2 : 1);

                        self.setB1200s(self.getB1200() / (double)maxCount >= 0.8 ? self.getB1200() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1220s(self.getB1220() / (double)maxCount >= 0.8 ? self.getB1220() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1240s(self.getB1240() / (double)maxCount >= 0.8 ? self.getB1240() / maxCount == 1 ? 3 : 2 : 1);

                        self.setB1300s(self.getB1300() / (double)maxCount >= 0.8 ? self.getB1300() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1320s(self.getB1320() / (double)maxCount >= 0.8 ? self.getB1320() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1340s(self.getB1340() / (double)maxCount >= 0.8 ? self.getB1340() / maxCount == 1 ? 3 : 2 : 1);

                        self.setB1700s(self.getB1700() / (double)maxCount >= 0.8 ? self.getB1700() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1720s(self.getB1720() / (double)maxCount >= 0.8 ? self.getB1720() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1740s(self.getB1740() / (double)maxCount >= 0.8 ? self.getB1740() / maxCount == 1 ? 3 : 2 : 1);

                        self.setB1800s(self.getB1800() / (double)maxCount >= 0.8 ? self.getB1800() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1820s(self.getB1820() / (double)maxCount >= 0.8 ? self.getB1820() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1840s(self.getB1840() / (double)maxCount >= 0.8 ? self.getB1840() / maxCount == 1 ? 3 : 2 : 1);

                        self.setB1900s(self.getB1900() / (double)maxCount >= 0.8 ? self.getB1900() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1920s(self.getB1920() / (double)maxCount >= 0.8 ? self.getB1920() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB1940s(self.getB1940() / (double)maxCount >= 0.8 ? self.getB1940() / maxCount == 1 ? 3 : 2 : 1);

                        self.setB2000s(self.getB2000() / (double)maxCount >= 0.8 ? self.getB2000() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB2020s(self.getB2020() / (double)maxCount >= 0.8 ? self.getB2020() / maxCount == 1 ? 3 : 2 : 1);
                        self.setB2040s(self.getB2040() / (double)maxCount >= 0.8 ? self.getB2040() / maxCount == 1 ? 3 : 2 : 1);

                    } else if (self.getMaxCount() == null || self.getMaxCount() == 0) {
                        //不限制
                        self.setMaxCount(0);
                    }
                    map.put("TwoDaysOrder", self);
                }**/
//            }
        }

        return map;
    }

    /**
     * 团课产品表
     *
     * @param userLevel
     * @param serviceType
     * @param storeId
     * @param courseId
     * @return
     */

	private Map<String, Object> getTeamCoureseList(int userLevel, int serviceType, int storeId, int courseId,
			UserInfo userInfo, Integer hasYearCardService) {
        Map<String, Object> map = new HashMap<String, Object>();
        serviceType = ServiceType.teamCourse.getIndex();
        
        ServicePriceExample serviceExample = new ServicePriceExample();
        serviceExample.or().andServiceTypeEqualTo(serviceType)
                .andCourseIdEqualTo(courseId).andLevelEqualTo(UserConstants.UserLevel.user.getIndex());
        List<ServicePrice> serviceList = servicePriceMapper.selectByExample(serviceExample);
        if (serviceList.size() > 0) {
            ServicePrice servicePrice = serviceList.get(0);
            //服务信息
            /*map.put("serviceName", servicePrice.getServiceName());*/
            // 查询折扣
            CityDiscount cityDiscount = cityDiscountMapper.queryCityDiscountByStoreId(servicePrice.getStoreId());
            
            // 查询该用户是否购买过此课程的订单
            Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(courseId, userInfo.getId(), serviceType);
            map.put("hasCourseOrder", hasCourseOrder > 0);
        	// 判断该用户是否拥有年卡权限

        	// 因为根据业务需求改变 用户购买团课是否享有VIP会员价格是根据用户在购买
            // 会员卡的时候是否勾选上团课免费的选项来决定用户时候拥有会员价格的
            hasYearCardService = userCourseVipServiceService.hasUserCourseVipService(userInfo.getId(),OrderContants.OrderType.team_course.getIndex()) == true ? 1 : 0;
            map.put("hasYearCardService",hasYearCardService); // 给一个临时可购买的身份

            //服务价格表
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            for (ServicePrice service : serviceList) {
                Map<String, Object> mapItem = new HashMap<String, Object>();
                mapItem.put("id", service.getId());
                // 会员 打折 非会员 原价
                if (service.getPrice() != null) {
                    mapItem.put("price", service.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                    mapItem.put("primePrice", service.getPrimePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                    mapItem.put("unitPrice", service.getPrimePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                } else {
                    mapItem.put("price", ((service.getPrimePrice()).multiply(cityDiscount.getVipDiscount())).setScale(2, BigDecimal.ROUND_HALF_UP));
                    mapItem.put("primePrice", service.getPrimePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                    mapItem.put("unitPrice", service.getPrimePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
                }
                resultList.add(mapItem);
                break; //有且只有一条记录
            }
            map.put("list", resultList);

            //课程信息
            CourseInfo courseInfo = this.courseInfoMapper.selectById(courseId);
            map.put("courseId", courseInfo.getId());
            map.put("waitPersonCount", courseInfo.getWaitCount());
            map.put("serviceName", courseInfo.getTitle());

            
            //课程时间
//            CourseScheduleExample example = new CourseScheduleExample();
//            example.or().andCourseIdEqualTo(courseId);
//            List<CourseSchedule> scheduleList = courseScheduleMapper.selectByExample(example);

            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(courseId);
            EntityWrapper<CourseSchedule> courseScheduleEntityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(courseScheduleEntityWrapper);

            if (scheduleList.size() > 0) {
                CourseSchedule schedule = scheduleList.get(0);
                String courseTime = DateUtils.format(schedule.getStartTime(), DateUtils.datePattern) + " " + schedule.getHourMin();
                map.put("courseTime", courseTime);
            }
            
            // 教练信息
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1,courseInfo.getId());
            map.put("coachName", coachInfo.getNickName());
            
            //门店信息
//            CourseStoreExample csExample = new CourseStoreExample();
//            csExample.or().andCourseIdEqualTo(courseInfo.getId());
//            List<CourseStore> courseStoreList = courseStoreMapper.selectByExample(csExample);

            CourseStore courseStoreDB = new CourseStore();
            courseStoreDB.setCourseId(courseInfo.getId());
            EntityWrapper<CourseStore> courseStoreEntityWrapper = new EntityWrapper<>(courseStoreDB);
            List<CourseStore> courseStoreList = courseStoreMapper.selectList(courseStoreEntityWrapper);

            if (courseStoreList.size() > 0) {
                Integer courseStoreId = courseStoreList.get(0).getStoreId();
                StoreInfo storeInfo = storeInfoMapper.selectById(courseStoreId);
                if (storeInfo != null) {
                    map.put("storeId", storeInfo.getId());
                    map.put("storeName", storeInfo.getStoreName());
                    if(storeInfo.getOpenTime() !=null){
                        map.put("storeOpenTime", DateUtils.format(storeInfo.getOpenTime(), DateUtils.shortTimePattern));
                    }
                    if(storeInfo.getCloseTime()!=null){
                        map.put("storeCloseTime", DateUtils.format(storeInfo.getCloseTime(), DateUtils.shortTimePattern));
                    }
                }
            }
        }

        return map;
    }

    /**
     * 私教课产品表
     *
     * @param userLevel
     * @param serviceType
     * @param storeId
     * @param courseId
     * @return
     */

    private Map<String, Object> getPrivateCourseList(int userLevel, int serviceType, int storeId, int courseId , UserInfo userInfo, Integer hasYearCardService) {
        Map<String, Object> map = new HashMap<>();
        serviceType = ServiceType.privateCourse.getIndex();

        ServicePriceExample serviceExample = new ServicePriceExample();
        serviceExample.or().andServiceTypeEqualTo(serviceType)
                .andCourseIdEqualTo(courseId);
        List<ServicePrice> serviceList = servicePriceMapper.selectByExample(serviceExample);

        if (serviceList.size() > 0) {
            ServicePrice servicePrice = serviceList.get(0);

            //服务信息
            map.put("serviceName", servicePrice.getServiceName());

            // 查询折扣
            CityDiscount cityDiscount = cityDiscountMapper.queryCityDiscountByStoreId(servicePrice.getStoreId());

            //服务价格表
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            for (ServicePrice service : serviceList) {
                Map<String, Object> mapItem = new HashMap<String, Object>();
                mapItem.put("id", service.getId());

                mapItem.put("primePrice", service.getPrimePrice());  //原价
                // 会员： 打折      非会员： 原价
                if (service.getPrice() != null) {
                    mapItem.put("price", service.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));  //原价
                } else {
                    mapItem.put("price", service.getPrimePrice().multiply(cityDiscount.getVipDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP));//优惠价,即会员价
                }
                if (userLevel == 2) {
                    map.put("discount", cityDiscount.getVipDiscount());

                } else {
                    map.put("discount", cityDiscount.getDiscount());
                }

//    			// 课次应从courseInfo 中定义. 单价 ＝ 原价 / 课次 订单现在按次计算 不需要按原价的 /课次得出
//        		double unitPrice = service.getPrimePrice().divide(BigDecimal.valueOf(service.getDuration().longValue()), 2, RoundingMode.HALF_UP).doubleValue();
//        		mapItem.put("unitPrice", unitPrice);
                resultList.add(mapItem);
                break;  //必须只有一条记录
            }
            map.put("list", resultList);

            //去餐券价格
            Map<String,Object> paramMap = new HashMap<>();
            paramMap.put("serviceType", ServiceType.mealCouponService.getType());
            if(storeId>0){
                paramMap.put("storeId",storeId);
            }
            List<ServicePrice> mealCouponServicePriceList = servicePriceMapper.selectServicePriceBy(paramMap);
            BigDecimal mealCouponPrice = ServiceConstans.defaultMealCouponPrice;
            if(mealCouponServicePriceList!=null && mealCouponServicePriceList.size()>0){
                mealCouponPrice= mealCouponServicePriceList.get(0).getPrice();
            }

            //课程信息
            CourseInfo courseInfo = courseInfoMapper.selectById(courseId);
            map.put("courseId", courseInfo.getId());
            map.put("minCount", courseInfo.getMinCount());
            map.put("isBuyOneClassLimit", courseInfo.getIsBuyOneClassLimit());
            map.put("mealCount",courseInfo.getMealCount());
            map.put("mealPrice",mealCouponPrice);
            
            // 私教课程需要分为 包含年卡课程和不包含年卡课程 
            // 包含年卡课程是不需要身份的验证的 其余的需要身份的验证
            if(courseInfo.getProductServiceDetailId() != null && courseInfo.getProductServiceDetailId() > 0) {
            	map.put("hasYearCardService",true); // 给一个临时可购买的身份
            	map.put("hasCourseOrder",false); // 可以多次购买
            }else {
            	// 需要身份的验证
            	// 查询该用户是否购买过此课程的订单
                Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(courseId, userInfo.getId(), serviceType);
                map.put("hasCourseOrder", false);
                
            	// 判断该用户是否拥有年卡权限
                map.put("hasYearCardService",hasYearCardService); // 给一个临时可购买的身份
            	
            }
            
            
//        	 课时数 私教现在是按单次销售 已不需要课时
//        	map.put("courseCount", servicePrice.getDuration().toString());

            // 教练信息
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1,courseInfo.getId());
            map.put("coachName", coachInfo.getNickName());
            
            //todo:门店信息 私教课有多个门店！！
//            CourseStoreExample csExample = new CourseStoreExample();
//            csExample.or().andCourseIdEqualTo(courseInfo.getId());
//            List<CourseStore> courseStoreList = courseStoreMapper.selectByExample(csExample);
            // 这里注释掉 
            /*CourseStore courseStoreDB = new CourseStore();
            courseStoreDB.setCourseId(courseInfo.getId());
            EntityWrapper<CourseStore> entityWrapper = new EntityWrapper<>(courseStoreDB);
            List<CourseStore> courseStoreList = courseStoreMapper.selectList(entityWrapper);*/
            // 要求返回返回多个门店名称 用 “、” 连接在一起
            String storeName = courseStoreMapper.getCourseStoreNameByCourseId(courseInfo.getId());
            if(!StringUtil.isEmpty(storeName)) {
            	 map.put("storeName", storeName.replaceAll(",", "、"));
            }else {
            	 map.put("storeName", storeName);
            }
            
            /*if (courseStoreList.size() > 0) {
                storeId = courseStoreList.get(0).getStoreId();
                StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
                if (storeInfo != null) {
                    map.put("storeName", storeInfo.getStoreName());
                }
            }*/
        }

        return map;
    }

    /**
     * 檬营 (获取产品信息 用于订单页面)
     *
     * @param userLevel
     * @param serviceType
     * @param storeId
     * @param courseId
     * @return
     */
    private Map<String, Object> getCampCoureseList(int userLevel, int serviceType, int storeId, int courseId , UserInfo userInfo, Integer hasYearCardService) {
        Map<String, Object> map = new HashMap<String, Object>();
        serviceType = ServiceType.campCourse.getIndex();

        ServicePriceExample serviceExample = new ServicePriceExample();
        serviceExample.or().andServiceTypeEqualTo(serviceType)
                .andCourseIdEqualTo(courseId)
                .andLevelEqualTo(UserConstants.UserLevel.user.getIndex());
        List<ServicePrice> serviceList = servicePriceMapper.selectByExample(serviceExample);
        if (serviceList.size() > 0) {
            ServicePrice servicePrice = serviceList.get(0);

            //服务信息
            /*map.put("serviceName", servicePrice.getServiceName());*/
            // 查询折扣
            CityDiscount cityDiscount = cityDiscountMapper.queryCityDiscountByStoreId(servicePrice.getStoreId());

            //服务价格表
            List<Map<String, Object>> resultList = new ArrayList<>();
            for (ServicePrice service : serviceList) {
                Map<String, Object> mapItem = new HashMap<>();
                mapItem.put("id", service.getId());

                mapItem.put("primePrice", service.getPrimePrice());  //原价
                if (service.getPrice() != null) {
                    mapItem.put("price", service.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));//优惠价,即会员价
                } else {
                    mapItem.put("price", service.getPrimePrice().multiply(cityDiscount.getVipDiscount()).setScale(2, BigDecimal.ROUND_HALF_UP));//优惠价,即会员价
                }
                mapItem.put("unitPrice", service.getPrimePrice());
                if (userLevel == 2) {
                    map.put("discount", cityDiscount.getVipDiscount());

                } else {
                    map.put("discount", cityDiscount.getDiscount());  //普通用户的折扣，默认1
                }
                resultList.add(mapItem);
            }
            map.put("list", resultList);

            //课程信息
            CourseInfoModel courseInfo = courseInfoMapper.queryCampCourseById(courseId);
            map.put("minCount", courseInfo.getMinCount());
            map.put("courseId", courseInfo.getId());
            map.put("maxCount", courseInfo.getMaxCount());
            map.put("currentCount", courseInfo.getCurrentCount());
            map.put("waitCount", orderInfoMapper.queryMaxWaitNumber(servicePrice.getId()));
            map.put("serviceName", courseInfo.getTitle());
            //课程时间
//            CourseScheduleExample example = new CourseScheduleExample();
//            example.or().andCourseIdEqualTo(courseId);
//            List<CourseSchedule> scheduleList = courseScheduleMapper.selectByExample(example);

            CourseSchedule courseScheduleDB = new CourseSchedule();
            courseScheduleDB.setCourseId(courseId);
            EntityWrapper<CourseSchedule> courseScheduleEntityWrapper = new EntityWrapper<>(courseScheduleDB);
            List<CourseSchedule> scheduleList = courseScheduleMapper.selectList(courseScheduleEntityWrapper);
            if (scheduleList.size() > 0) {
                CourseSchedule schedule = scheduleList.get(0);
                //DateUtils.format(schedule.getStartTime(), DateUtils.datePattern) + " " + schedule.getHourMin();
                map.put("courseTime", courseInfo.getStartEndTime());
                map.put("periods", schedule.getPeriods());
            }
            
            // 教练信息
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoByCourseId(1,courseInfo.getId());
            map.put("coachName", coachInfo.getNickName());
            
            // 查询该用户是否购买过此课程的订单
            Integer hasCourseOrder = orderInfoMapper.checkUserIsHasThisCourseOrderByCourseIdAndUserIdAndOrderType(courseId, userInfo.getId(), serviceType);
            map.put("hasCourseOrder", hasCourseOrder > 0);
        	
        	// 判断该用户是否拥有年卡权限
            map.put("hasYearCardService",hasYearCardService); // 给一个临时可购买的身份
            
            //门店信息
//            CourseStoreExample csExample = new CourseStoreExample();
//            csExample.or().andCourseIdEqualTo(courseInfo.getId());
//            List<CourseStore> courseStoreList = courseStoreMapper.selectByExample(csExample);

            CourseStore courseStoreDB = new CourseStore();
            courseStoreDB.setCourseId(courseInfo.getId());
            EntityWrapper<CourseStore> courseStoreEntityWrapper = new EntityWrapper<>(courseStoreDB);
            List<CourseStore> courseStoreList = courseStoreMapper.selectList(courseStoreEntityWrapper);
            	
            if (courseStoreList.size() > 0) {
                Integer courseStoreId = courseStoreList.get(0).getStoreId();
                StoreInfo storeInfo = storeInfoMapper.selectById(courseStoreId);
                if (storeInfo != null) {
                    map.put("storeId", storeInfo.getId());
                    map.put("storeName", storeInfo.getStoreName());
                }
            }
        }

        return map;
    }

    /**
     * 获取会员价格列表
     */
    @Override
    public Map<String, Object> getViplist(int userId,int productId) {
    	
    	
        Map<String, Object> map = new HashMap<String, Object>();
        List<ProductServiceDetail> listProdecuDetail = productServiceDetailMapper.queryProductServiceDetailListByProduceId(productId);
        //普通会员价
        List<VipProductModel> vipModelList = new ArrayList<VipProductModel>();
        String startDate = "";
        Date ys_date = new Date();// 预售结束时间
        for (ProductServiceDetail psd : listProdecuDetail) {
            VipProductModel model = toVipProductCard(psd);
            vipModelList.add(model);
            ys_date = psd.getPdDateline();
        }
        map.put("vipList", vipModelList);
        map.put("dateLin", vipModelList.get(0).getDateline().toString());
        logger.info("==========================ys_date:"+DateUtils.toDateString(ys_date));
        ProductService productServiceM = productServiceMapper.selectById(productId);
       
        if(productServiceM != null){
        	UserProductService ups = 
        			userProductServiceMapper.queryUserProductServiceByUserIdAndType(userId,productServiceM.getPServiceType());
        	
        	if(ups != null){
        		// 获取用户连续续费，续费 ，新增  的开始或者结束时间
        		if(ups.getIsvalid() == UserProductServiceConstants.ISVALID 
        				&& !UserProductServiceConstants.productServiceType.user.getType().equals(ups.getProductServiceType())){
        			// 如果预售日期小于用户服务的结束时间就按照预售日期来
        			if(ys_date.compareTo(ups.getEndDate()) > 0){
        				map.put("startDate", DateUtils.toDateString(ys_date));
        			}else{
        				// 如果预售日期用户服务的结束时间就按照预售日期来
        				map.put("startDate", DateUtils.toDateString(DateUtils.AddDays(ups.getEndDate(), -1)));
        			}
        		}else{
        			if(ys_date.compareTo(new Date()) > 0){
        				map.put("startDate", DateUtils.toDateString(ys_date));
        			}else{
        				map.put("startDate", DateUtils.toDateString((new Date())));
        			}
        			
        		}
        	}else{
        		if(ys_date.compareTo(new Date()) > 0){
    				map.put("startDate", DateUtils.toDateString(ys_date));
    			}else{
    				map.put("startDate", DateUtils.toDateString((new Date())));
    			}
        	}
        }else{
        	map.put("startDate", DateUtils.toDateString((new Date())));
        }
        
        return map;
    }

  
    private VipProductModel toVipProduct(UserDiscount userDiscount) {
        VipProductModel model = new VipProductModel();
        model.setId(userDiscount.getId());
        model.setMonth(Integer.valueOf(userDiscount.getType()));
        model.setPrice((userDiscount.getPrimePrice().multiply(BigDecimal.valueOf(userDiscount.getDiscount()))).setScale(2, BigDecimal.ROUND_HALF_UP) + "");
        model.setPrimePrice(userDiscount.getPrimePrice() + "");
        model.setRecommend(Integer.valueOf(userDiscount.getRecommend()));
        model.setFreeday(userDiscount.getFreeday());
        model.setDateline(userDiscount.getDateline());
        return model;
    }

    /**
     * 获取商品类型的价钱
     */
    @Override
    public ServicePrice queryServicePrice(int userLevel, int serviceType, int storeId, int courseId) {
        ServicePriceExample example = new ServicePriceExample();
        // 自助健身
        if (serviceType == 4) {
            example.or().andLevelEqualTo(userLevel).andServiceTypeEqualTo(serviceType).andStoreIdEqualTo(storeId);
        }
        // 会员
        else if (serviceType == 5) {
            example.or().andLevelEqualTo(userLevel).andServiceTypeEqualTo(serviceType).andStoreIdEqualTo(storeId);
        }
        // 团课 檬营 私教
        else {
            example.or().andLevelEqualTo(userLevel).andServiceTypeEqualTo(serviceType).andStoreIdEqualTo(storeId).andCourseIdEqualTo(courseId);
        }
        List<ServicePrice> servicePriceList = servicePriceMapper.selectByExample(example);
        return servicePriceList.get(0);
    }

    
    /**
     * 包月卡返回前段对象
     * @param productServiceDetail
     * @return
     */
    private VipProductModel toVipProductCard(ProductServiceDetail productServiceDetail) {
        VipProductModel model = new VipProductModel();
        model.setId(productServiceDetail.getId());
        model.setMonth(Integer.valueOf(productServiceDetail.getPdType()));
        model.setPrice((productServiceDetail.getPdPrimePrice().multiply(BigDecimal.valueOf(productServiceDetail.getPdDiscount()))).setScale(2, BigDecimal.ROUND_HALF_UP) + "");
        model.setPrimePrice(productServiceDetail.getPdPrimePrice() + "");
        model.setRecommend(Integer.valueOf(productServiceDetail.getPdRecommend()));
        model.setFreeday(productServiceDetail.getPdFreeday());
        model.setDateline(new java.sql.Date(productServiceDetail.getPdDateline().getTime()));
        return model;
    }
    
    /**
     * 获取体测券的支付前的订单详情
     * @param userLevel
     * @param serviceType
     * @param storeId
     * @param courseId
     * @return
     */
    private Map<String,Object> getPhysicalCouponList(int userLevel, int serviceType, int storeId, int courseId, UserInfo userInfo, Integer hasYearCardService){
    	Map<String, Object> map = new HashMap<String, Object>();
    	
    	// 判断该用户是否拥有年卡权限
    	map.put("hasYearCardService",hasYearCardService); // 给一个临时可购买的身份
    	map.put("hasCourseOrder",false); // 让他不限次数的购买
    	// stpe 1 查询是否有优惠价
    	List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
    	Map<String, Object> mapItem = new HashMap<String, Object>();
    	ServicePriceResultModel servicePriceResultModel = servicePriceMapper.queryCoursePriceByCourseId(courseId);
    	mapItem.put("price", servicePriceResultModel.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
        mapItem.put("primePrice", servicePriceResultModel.getPrimePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
        mapItem.put("unitPrice", servicePriceResultModel.getPrimePrice().setScale(2, BigDecimal.ROUND_HALF_UP));
        mapItem.put("serviceId", servicePriceResultModel.getServiceId());
        mapItem.put("id", servicePriceResultModel.getServiceId());
        resultList.add(mapItem);
        map.put("list", resultList);
        map.put("courseId", courseId);
        map.put("serviceName", servicePriceResultModel.getServiceName());
    	return map;
    }
}
